package org.dynamo.database.reverse.config.reader.internal;
/*******************************************************************************
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Jean Neveux - initial API and implementation
 *******************************************************************************/
import java.io.IOException;
import java.util.Collections;

import org.dynamo.database.reverse.emf.metadata.Catalog;
import org.dynamo.database.reverse.emf.metadata.MetadataFactory;
import org.dynamo.database.reverse.emf.metadata.MetadataPackage;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

public class MetadataLoader {
	
	private static ResourceSet resourceSet = new ResourceSetImpl();

	{
		resourceSet.getPackageRegistry().put(MetadataPackage.eNS_URI,MetadataPackage.eINSTANCE);
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
	}


	public static MetadataFactory initModel() {
		return MetadataFactory.eINSTANCE;
	}

	public static void save(String path, Catalog catalog) {
		URI fileURI = URI.createPlatformResourceURI(path, true);
		Resource resource = resourceSet.createResource(fileURI);
		resource.getContents().add( catalog );
		try {
			resource.save(Collections.EMPTY_MAP);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Catalog load(String path) {

		Resource load_resource = resourceSet.getResource(
		    URI.createPlatformResourceURI(path,true),true);

		Catalog catalog = (Catalog)
		    load_resource.getContents().get(0);

		return catalog;
	}
}
